package com.wft.design.upms.controller;

import com.wft.design.common.core.util.TreeUtils;
import com.wft.design.common.core.validation.AddValidation;
import com.wft.design.common.core.validation.EditValidation;
import com.wft.design.common.security.annotation.PreAuthorize;
import com.wft.design.common.security.service.AuthenticationManager;
import com.wft.design.upms.entity.SysMenu;
import com.wft.design.upms.service.SysMenuService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author WFT
 * @date 2020/2/7
 * description: 系统菜单控制器
 */
@RestController
@RequiredArgsConstructor
@RequestMapping(value = "/menu")
public class MenuController {

    private final SysMenuService menuService;
    private final AuthenticationManager authenticationManager;

    /**
     * 获取菜单树形列表
     * @return java.util.List<SysMenu>
     */
    @GetMapping(value = "/tree")
    @PreAuthorize
    public List<SysMenu> getTree(){
        return TreeUtils.build(this.menuService.selectList());
    }

    /**
     * 根据Id获取菜单信息
     * @param menuId java.lang.Long
     * @return com.wft.design.upms.entity.SysMenu
     */
    @GetMapping(value = "/{menuId}")
    @PreAuthorize
    public SysMenu get(@PathVariable(value = "menuId")Long menuId){
        return this.menuService.selectById(menuId);
    }

    /**
     * 创建菜单
     * @param menu com.wft.design.upms.entity.SysMenu
     */
    @PostMapping
    @PreAuthorize
    public void add(@Validated(value = AddValidation.class) @RequestBody SysMenu menu){
        //  默认为根节点
        if (null == menu.getPid()){
            menu.setPid(0L);
        }
        //  创建菜单
        this.menuService.createMenu(menu);
    }

    /**
     * 根据Id修改菜单信息
     * @param menu com.wft.design.upms.entity.SysMenu
     */
    @PutMapping
    @PreAuthorize
    public void edit(@Validated(value = EditValidation.class) @RequestBody SysMenu menu){
        this.menuService.updateMenu(menu);
    }

    /**
     * 根据Id删除菜单信息
     * @param menuId java.lang.Long
     */
    @DeleteMapping(value = "/{menuId}")
    @PreAuthorize
    public void delete(@PathVariable(value = "menuId") Long menuId){
        this.menuService.deleteMenuById(menuId);
    }

    /**
     * 获取当前用户可视的菜单列表
     * @param pid java.lang.Long
     * @return java.util.List<SysMenu>
     */
    @PreAuthorize
    @GetMapping(value = "/getMeMenus")
    public List<SysMenu> getMeMenus(Long pid) {
        //  当前用户的权限列表
        Collection<String> authorities = this.authenticationManager.getAuthentication().getAuthorities();
        if (authorities.isEmpty()){
            return new ArrayList<>(0);
        }
        return TreeUtils.build(this.menuService.selectMenuListByPid(pid,authorities),pid);
    }

}
